const { app, BrowserWindow,ipcMain,dialog } = require('electron/main')
const path = require('node:path')
const {existsSync,readdirSync} = require("node:fs");
const fs = require("node:fs");
const isDevelopment = !app.isPackaged;


const createWindow = () => {
    const win = new BrowserWindow({
        width: 1000,
        height: 800,
        icon: ('static/img/logo.ico'),
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        }
    })

    win.loadFile('index.html')

    //win设置
    win.setMenuBarVisibility(false); //设置菜单不可见
    win.center(); //窗口居中

    if (isDevelopment) {
        win.webContents.openDevTools(); //打开开发者模式
    }

    initIpcMain()
}

//高DPI支持
if (process.platform === 'win32') {
    app.commandLine.appendSwitch('high-dpi-support', 'true');
    app.commandLine.appendSwitch('force-device-scale-factor', '1');
}
app.disableDomainBlockingFor3DAPIs();   // 关闭3D api, 提高兼容性
app.disableHardwareAcceleration();      // 关闭硬件加速, 减少渲染问题

//绑定App启动时创建窗口
app.whenReady().then(() => {
    createWindow()

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow()
        }
    })
})
//在窗口关闭时，整个App关闭
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

function initIpcMain() {
    ipcMain.handle('specify_workspace',  async (event, ...args) => {
        //判断工作空间中是否存在配置文件config.json
        console.log("start specify_workspace function")
        try{
            //1.打开文件夹选择器
            const result = await dialog.showOpenDialog({
                properties: ['openDirectory'],
            });
            // 是否取消
            console.log(result.canceled);
            // 文件路径
            console.log(result.filePaths);
            if (isDevelopment) { console.log(`文件取消状态: ${result.canceled}, 选择的文件路径: ${result.filePaths}`); }
            if (!result.canceled) {
                //判断文件夹中是否存在config.json
                if (existsSync(path.join(result.filePaths[0], 'config.json'))) {
                    //如果存在，返回文件夹路径
                    if (isDevelopment) { console.log(result.filePaths[0]); }
                    return {
                        success: true,
                        path: result.filePaths[0]
                    };

                }else {
                    //判断文件夹是否为空文件夹
                    if(readdirSync(result.filePaths[0]).length > 0){
                        //如果不为空文件夹，提示用户
                        dialog.showMessageBox({
                            type: 'error',
                            title: '错误',
                            message: '该文件夹不为空文件夹,请选择一个空文件夹',
                            buttons: ['确定']
                        });
                        return;
                    }
                    // console.log(`无配置文件,新建一个配置文件:${result.filePaths[0]}/config.json`);
                    // //如果不存在，新建一个config.json
                    // const fs = require('node:fs');
                    // fs.writeFileSync(path.join(result.filePaths[0], 'config.json'), '{}');
                    // //返回文件夹路径
                    // console.log(`新建配置文件成功:${result.filePaths[0]}/config.json`);
                    return {
                        success: true,
                        path: result.filePaths[0]
                    };
                }
            }

        }catch (error) {
            console.error('Error opening directory:', error);
            return {
                success: false,
                error: error.message
            };
        }
        console.log("close specify_workspace function")
    })
}